﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ScreenTranslate
{
    public class Server
    {
        private Teacher teacher;
        private List<Client> clients;
        private Socket server;
        int port;

        public Server(Teacher teacher,int port)
        {
            this.teacher = teacher;
            clients = new List<Client>();
            this.port = port;
        }

        public void StartServer()
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.Bind(new IPEndPoint(IPAddress.Any,port));
            server.Listen(0);
            server.BeginAccept(AcceptCallBack, null);
        }

        public void Send(byte[] bytes)
        {
            int count = clients.Count;
            if (count <= 0)
                return;
            try {
                byte[] data = Message.PackData(bytes);
                for (int i = 0; i < count; i++)
                {
                    clients[i].Send(data);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("发送数据异常");
            }
        }

        private void AcceptCallBack(IAsyncResult ar)
        {
            try
            {
                Socket clientSocket = server.EndAccept(ar);
                Client client = new Client(clientSocket, this);
                if (clients.Contains(client) == false)
                {
                    clients.Add(client);
                }
                server.BeginAccept(AcceptCallBack, null);
            }
            catch (Exception e)
            {
               
            }
        }
        public void RemoveClient(Client client)
        {
            try
            {
                lock (clients)
                {
                    clients.Remove(client);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("移除客户端异常:" + e);
            }
        }

        public void Close()
        {
            try
            {
                int count = clients.Count;
                for (int i = 0; i < count; i++)
                {
                    clients[i].Close();
                }
                if (server != null)
                {
                    server.Close();
                }
            }
            catch (Exception e)
            {

            }
        }
    }
}
